<template>
	<view class="login">
		<view class="main-header">

		</view>

		<view class="logo">
			<image src="../../static/images/logo.png"></image>
		</view>
		<view class="logo1">
			<image src="../../static/images/logo1.png"></image>
		</view>
		<view class="logo2">
			<image src="../../static/images/logo2.png"></image>
		</view>

		<view class="box">
			<view class="item">
				<view class="icon">
					<image src="../../static/images/account.png"></image>
				</view>
				<view class="shuru"><input type="text" class="in" v-model="mobile" placeholder="请输入账号" /></view>
			</view>
			<view class="item">
				<view class="icon">
					<image src="../../static/images/pwd.png"></image>
				</view>
				<view class="shuru"><input type="text" class="in" password v-model="password" placeholder="请输入登录密码" />
				</view>
			</view>

		</view>

		<view class="btn-box">

			<view @click="handleLogin">登录</view>

		</view>

		<view class="line">
			<u-line color="#BBBBBB" />
		</view>

		<view class="wechat-box">
			<view>
				<view class="wechat" @click.stop="getUserProfile">
					<image src="../../static/images/phone.png"></image>
				</view>

				<button class="button btn-normal name" @click.stop="getUserProfile">手机授权登录</button>
			</view>
		</view>

		<u-popup v-model="showRealName" mode="bottom" height="700rpx">
			<!-- 微信授权手机号一键登录 -->
			<view style="padding: 30rpx 20rpx;">
				<view>
					<view
						style="color: rgba(16, 16, 16, 1);text-align: center;height: 40rpx;line-height: 40rpx;font-size: 28rpx;">
						获取你的头像、昵称</view>
					<view class="p-logo">
						<button class="btn-normal" open-type="chooseAvatar" @click="onClickAvatar()"
							@chooseavatar="onChooseAvatar">
							<avatar-image :url="avatarUrl" :width="100" />
						</button>
					</view>

					<view class="shuru-name">
						<view class="shuru"><input type="text" class="in-name"  v-model="form.nickName"
								placeholder="请输入您的真实姓名" placeholder-style="color:red"/></view>
					</view>
				</view>
				<view class="wechat-auth">


					<view class="wechat-auth-container">

						<text class="title" @click="handleSubmit()">确认保存</text>
					</view>

				</view>
			</view>
		</u-popup>

		<u-popup v-model="showMobile" mode="bottom" height="700rpx">
			<!-- 微信授权手机号一键登录 -->
			<view style="padding: 30rpx 20rpx;">
				<view>

					<view
						style="color: rgba(16, 16, 16, 1);text-align: center;height: 40rpx;line-height: 40rpx;font-size: 28rpx;">
						获取你的手机号</view>
					<view class="p-logo">
						<image src="../../static/images/logo.png"></image>
					</view>
					<view class="p-logo1">
						<image src="../../static/images/logo1.png"></image>
					</view>
					<view class="xieyi">
						<view>
							<checkbox-group>
								<label>
									<checkbox class="checkbox-backgroun-yellow" value="cb" checked="true"
										style="transform:scale(0.6)" />
								</label>

							</checkbox-group>
						</view>
						<view style="font-size: 24rpx;line-height: 40rpx;">已阅读并同意《用户协议》和《隐私政策》</view>

					</view>
				</view>
				<view class="wechat-auth">


					<button class="btn-normal" open-type="getPhoneNumber"
						@getphonenumber="handelMpWeixinMobileLogin($event)" @click="clickPhoneNumber">
						<view class="wechat-auth-container">

							<text class="title">手机号快捷登录</text>
						</view>
					</button>
				</view>
			</view>
		</u-popup>



	</view>
</template>

<script>
	import Main from './components/main'
	import MpWeixin from './components/mp-weixin'
	import SettingKeyEnum from '@/common/enum/setting/Key'
	import SettingModel from '@/common/model/Setting'
	import * as Verify from '@/utils/verify'
	import AvatarImage from '@/components/avatar-image'
	import * as UserApi from '@/api/user'
	import * as UploadApi from '@/api/upload'
	import store from '@/store'
	import {
		isEmpty
	} from '@/utils/util'
	export default {
		components: {
			Main,
			MpWeixin,
			AvatarImage
		},

		data() {
			return {
				// 头像路径 (用于显示)
				avatarUrl: '',
				// 临时图片 (用于上传)
				tempFile: null,
				// 表单数据
				form: {
					avatarId: '',
					nickName: ''
				},
				showRealName: false,
				showMobile: false,
				// 数据加载完成 [防止在微信小程序端onLoad和view渲染同步进行]
				isLoad: false,
				// 是否显示微信小程序授权登录
				isMpWeixinAuth: false,
				// 是否存在第三方用户信息
				isParty: false,
				password: '',
				mobile: '',
				// 第三方用户信息数据
				partyData: {}
			}
		},

		/**
		 * 生命周期函数--监听页面加载
		 */
		async onLoad(options) {
			console.log('login onLoad')
			// 设置当前是否显示微信小程序授权登录
			//await this.setShowUserInfo()
			// 数据加载完成
			//this.isLoad = true
			console.log('isLoad', true)
		},

		methods: {

			// 点击头像按钮事件
			onClickAvatar() {
				// #ifdef MP-WEIXIN
				return
				// #endif
				this.chooseImage()
			},

			// 选择头像事件 - 仅限微信小程序
			// #ifdef MP-WEIXIN
			onChooseAvatar({
				detail
			}) {
				const app = this
				app.avatarUrl = detail.avatarUrl
				app.tempFile = {
					path: app.avatarUrl
				}
			},
			// #endif

			// 选择图片
			chooseImage() {
				const app = this
				// 选择图片
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success({
						tempFiles
					}) {
						app.tempFile = tempFiles[0]
						app.avatarUrl = app.tempFile.path
					}
				});
			},

			// 上传图片
			uploadFile() {
				const app = this
				return UploadApi.image([app.tempFile])
					.then(fileIds => {
						app.form.avatarId = fileIds[0]
						app.tempFile = null
						return true
					})
					.catch(() => {
						app.disabled = false
						return false
					})
			},

			// 确认修改
			async handleSubmit() {
				const app = this
				// 判断是否重复提交
				if (app.disabled === true) return
		
				
				
					// 先上传头像图片
					if (app.tempFile && !await app.uploadFile()) {
						uni.showToast({
							title:'请上传头像',
							icon:'none'
						})
						return
					}
					
					if(app.form.nickName==''){
						uni.showToast({
							title:'请填写真实姓名',
							icon:'none'
						})
						
						return
					}
					
					// 按钮禁用
					app.disabled = true
					
					// 提交保存个人信息
					UserApi.personal({
							form: app.form
						})
						.then(result => {
							//app.$toast(result.message)
							setTimeout(() => {
								app.disabled = false
								uni.navigateBack()
							}, 1500)
						})
						.catch(err => app.disabled = false)
				
			},

			// 点击登录
			handleLogin() {
				const app = this
				app.submitLogin()
			},

			// 确认登录
			submitLogin() {
				const app = this

				if (app.mobile == '') {
					this.$toast('请先输入账号')
					return false
				}
				if (app.pwd == '') {
					this.$toast('请先输入密码')
					return false
				}
				app.isLoading = true
				store.dispatch('Login', {
						pwd: app.password,
						mobile: app.mobile,
						isParty: app.isParty,
						partyData: app.partyData
					})
					.then(result => {
						// 显示登录成功
						app.$toast(result.message)
						// 相应全局事件订阅: 刷新上级页面数据
						uni.$emit('syncRefresh', true)
						// 跳转回原页面
						setTimeout(() => app.onNavigateBack(1), 2000)
					})
					.catch(err => {
						// 跳转回原页面
						if (err.result.data.isBack) {
							setTimeout(() => app.onNavigateBack(1), 2000)
						}
					})
					.finally(() => app.isLoading = false)
			},


			// 按钮点击事件: 获取微信手机号按钮
			// 实现目的: 在getphonenumber事件触发之前获取微信登录code
			// 因为如果在getphonenumber事件中获取code的话,提交到后端的encryptedData会存在解密不了的情况
			async clickPhoneNumber() {
				this.code = await this.getCode()
			},

			// 微信授权获取手机号一键登录
			// getphonenumber事件的回调方法
			async handelMpWeixinMobileLogin({
				detail
			}) {
				const app = this
				if (detail.errMsg != 'getPhoneNumber:ok') {
					console.log('微信授权获取手机号失败', detail.errMsg)
					// app.$error(detail.errMsg)
					return
				}
				app.isLoading = true
				store.dispatch('LoginMpWxMobile', {
						code: app.code,
						encryptedData: detail.encryptedData,
						iv: detail.iv,
						isParty: app.isParty,
						partyData: app.partyData,
						refereeId: store.getters.refereeId
					})
					.then(result => {
						//如果未填姓名
						console.log(result)
						if(result.data.real_name==''){
							app.showRealName=true
							app.showMobile=false
						}else{
							// 显示登录成功
							app.$toast(result.message)
							// 相应全局事件订阅: 刷新上级页面数据
							uni.$emit('syncRefresh', true)
							// 跳转回原页面
							setTimeout(() => app.onNavigateBack(1), 2000)
						}
					
					})
					.catch(err => {
						const resultData = err.result.data
						// 显示错误信息
						if (isEmpty(resultData)) {
							app.$toast(err.result.message)
						}
						// 跳转回原页面
						if (resultData.isBack) {
							setTimeout(() => app.onNavigateBack(1), 2000)
						}
					})
					.finally(() => app.isLoading = false)
			},


			/**
			 * 登录成功-跳转回原页面
			 */
			onNavigateBack(delta = 1) {
				const pages = getCurrentPages()
				if (pages.length > 1) {
					uni.navigateBack({
						delta: Number(delta || 1)
					})
				} else {
					this.$navTo('pages/index/index')
				}
			},

			// 获取商城基本信息
			getStoreInfo() {
				SettingModel.item('store').then(store => this.storeInfo = store)

				// SettingModel.h5Url(true)
			},

			// 获取code
			// https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
			getCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: res => {
							console.log('code', res.code)
							resolve(res.code)
						},
						fail: reject
					})
				})
			},


			// 获取微信用户信息(新版)
			getUserProfile() {
				const app = this
				wx.canIUse('getUserProfile') && wx.getUserProfile({
					lang: 'zh_CN',
					desc: '获取用户相关信息',
					success({
						userInfo
					}) {
						console.log('用户同意了授权')
						console.log('userInfo：', userInfo)
						// 授权成功事件
						app.onAuthSuccess(userInfo)
					},
					fail() {
						console.log('用户拒绝了授权')
					}
				})
			},

			// 授权成功事件
			// 这里分为两个逻辑:
			// 1.将code和userInfo提交到后端，如果存在该用户 则实现自动登录，无需再填写手机号
			// 2.如果不存在该用户, 则显示注册页面, 需填写手机号
			// 3.如果后端报错了, 则显示错误信息
			async onAuthSuccess(userInfo) {
				const app = this
				// 提交到后端
				store.dispatch('LoginMpWx', {
						partyData: {
							code: await app.getCode(),
							oauth: 'MP-WEIXIN',
							userInfo
						},
						refereeId: store.getters.refereeId
					})
					.then(result => {
						// 一键登录成功
						app.$toast(result.message)
						// 相应全局事件订阅: 刷新上级页面数据
						uni.$emit('syncRefresh', true)
						// 跳转回原页面
						setTimeout(() => app.onNavigateBack(), 2000)
					})
					.catch(err => {
						const resultData = err.result.data
						// 显示错误信息
						if (isEmpty(resultData)) {
							app.$toast(err.result.message)
						}
						// 跳转回原页面
						if (resultData.isBack) {
							setTimeout(() => app.onNavigateBack(1), 2000)
						}
						// 判断还需绑定手机号
						if (resultData.isBindMobile) {
							app.showMobile = true
							app.onEmitSuccess(userInfo)
						}
					})
			},

			// 将oauth提交给父级
			// 这里要重新获取code, 因为上一次获取的code不能复用(会报错)
			async onEmitSuccess(userInfo) {
				const app = this
				app.$emit('success', {
					oauth: 'MP-WEIXIN', // 第三方登录类型: MP-WEIXIN
					code: await app.getCode(), // 微信登录的code, 用于换取openid
					userInfo // 微信用户信息
				})
			},

			/**
			 * 设置当前是否显示微信小程序授权登录
			 *  - 条件1: 只有微信小程序才显示获取用户信息按钮
			 *  - 条件2: 后台设置是否已开启该选项 [后台-客户端-注册设置]
			 */
			async setShowUserInfo() {
				console.log('setShowUserInfo start')
				const app = this
				// 判断当前客户端是微信小程序, 并且支持getUserProfile接口
				const isMpWeixin = app.platform === 'MP-WEIXIN' && wx.canIUse('getUserProfile')

				// 获取后台设置
				await SettingModel.item(SettingKeyEnum.REGISTER.value, false)
					.then(setting => {
						app.isMpWeixinAuth = isMpWeixin && setting.isOauthMpweixin
						console.log('setShowUserInfo complete')
					})
			},

			// 获取到用户信息的回调函数
			onGetUserInfoSuccess({
				oauth,
				code,
				userInfo
			}) {
				// 记录第三方用户信息数据
				this.partyData = {
					oauth,
					code,
					userInfo
				}
				// 显示注册页面
				this.onShowRegister()
			},

			// 显示注册页面
			onShowRegister() {
				// 是否显示微信小程序授权登录
				this.isMpWeixinAuth = false
				// 已获取到了第三方用户信息
				this.isParty = true
			}
		}
	}
</script>

<style lang="scss" scoped>
	.xieyi {
		display: flex;
		justify-content: center;
	}

	.shuru-name {
		margin: 40rpx auto;
		width: 426rpx;
		height: 82rpx;
		line-height: 40rpx;
		border: 1px solid #E8E8E8;
		border-radius: 60rpx;
		display: flex;
	}
	.in-name {
		height: 82rpx;
		line-height: 40rpx;
		padding-left: 20rpx;
		
		
	}
	

	.p-logo {
		display: flex;
		justify-content: center;
		padding: 20rpx 0;
	}

	.p-logo image {
		width: 232rpx;
		height: 120rpx;
	}

	.p-logo1 {
		display: flex;
		justify-content: center;
	}

	.p-logo1 image {
		width: 462rpx;
		height: 90rpx;
	}

	// 微信授权登录
	.wechat-auth {
		width: 438rpx;
		margin: 20rpx auto 0 auto;

		.wechat-auth-container {
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 60rpx;
			font-size: 28rpx;
			height: 84rpx;
			background: linear-gradient(180deg, rgba(22, 132, 252, 1) 0%, rgba(100, 174, 255, 1) 100%);
			color: rgba(255, 255, 255, 1);
		}


	}

	.wechat-box {
		display: flex;
		justify-content: center;
	}

	.wechat {

		display: flex;
		justify-content: center;
	}

	.name {
		color: #989898;
		font-size: 24rpx;
	}

	.wechat image {
		width: 92rpx;
		height: 92rpx;
	}

	.line {
		width: 660rpx;
		padding-bottom: 20rpx;
		margin: 0 auto;
	}

	.btn-box {
		margin: 80rpx auto;
		width: 654rpx;
		height: 100rpx;
		line-height: 100rpx;
		border-radius: 60rpx;
		text-align: center;
		font-size: 36rpx;
		background: linear-gradient(180deg, rgba(22, 132, 252, 1) 0%, rgba(100, 174, 255, 1) 100%);
		color: rgba(255, 255, 255, 1);
	}

	.main-header {

		padding-top: 102rpx;
	}

	.item {
		margin: 40rpx auto;
		width: 660rpx;
		height: 94rpx;
		line-height: 40rpx;
		border: 1px solid rgba(22, 132, 252, 1);
		border-radius: 60rpx;
		display: flex;
	}

	.in {
		height: 94rpx;
		line-height: 40rpx;
		padding-left: 20rpx;
	}

	.shuru {
		width: 75%;
	}

	.icon {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 94rpx;
		width: 15%;

	}

	.icon image {
		width: 48rpx;
		height: 48rpx;
	}

	.logo {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.logo image {
		width: 360rpx;
		height: 186rpx;
	}

	.logo1 {

		display: flex;
		justify-content: center;
		align-items: center;
	}

	.logo1 image {
		width: 720rpx;
		height: 140rpx;
	}

	.logo2 {

		display: flex;
		justify-content: center;
		align-items: center;
	}

	.logo2 image {
		width: 360rpx;
		height: 140rpx;
	}
</style>